package com.snapp.util.service.db.mapping;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class CoreHandlers {
	private static Logger logger = Logger.getLogger(CoreHandlers.class);
	
	public static class IntegerHandler extends TypeHandler {
		private static final long serialVersionUID = -8654386417638282516L;

		public IntegerHandler() {}
		
		public Class<?>[] getClasses() {
			return new Class<?>[]{Integer.class};
		}
		
		public void process(PreparedStatement ps, Integer index, Object objToHandle) {
			try {
				ps.setInt((int)index, ((Integer)objToHandle).intValue());
			} catch (SQLException e) {
				logger.error("Error processing IntegerHandler!", e);
			}
			
		}
		
	}
	
	public static class FileHandler extends TypeHandler {
		private static final long serialVersionUID = 6006394746291092982L;
		private FileInputStream stream = null;
		private File file = null;
		
		public FileHandler(){}
		
		public Class<?>[] getClasses() {
			return new Class<?>[]{File.class};
		}

		/* (non-Javadoc)
		 * @see com.snapp.util.service.db.mapping.TypeHandler#process(java.sql.PreparedStatement, java.lang.Integer, java.lang.Object)
		 */
		public void process(PreparedStatement ps, Integer index, Object objToHandle) {
			file = (File)objToHandle;
			try {
				
				stream = new FileInputStream(file);
				
				ps.setBinaryStream((int)index, stream, (int)file.length());
			
			} catch(Exception e) {
				logger.error("Error adding file to prepared statement!", e);
			} 
		}

		// close the stream
		public void close() {
			try {
				stream.close();
				file.delete();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}


	}

}
